﻿using Prism.Commands;
using Prism.Regions;
using Prism.Services.Dialogs;
using SmartPlant.WinCore.Helper;
using System;
using System.Linq;
using System.Windows.Input;
using Unity;

namespace SmartPlant.Core.Mvvm
{
    /// <summary>
    /// 区域视图基类，包含基本的视图加载命令、视图关闭命令等。
    /// </summary>
    public abstract class RegionViewModelBase : SmartViewModel, INavigationAware, IConfirmNavigationRequest
    {
        /// <summary>
        /// 是否为系统加载中。
        /// </summary>
        protected bool _isLoding = false;
        private bool isSelected;
        private RegionTitle _title;
        private DelegateCommand<object> _closeCommand;
        private DelegateCommand<object> _dataLoadCommand;
        private readonly IDialogService _dialogService;
        private readonly IUnityContainer _unityContainer;

        protected string UriPath { get; set; }

        /// <summary>
        /// 初始化<see cref="RegionViewModelBase"/>对象。
        /// </summary>
        /// <param name="regionManager"></param>
        /// <param name="unityContainer"></param>
        /// <param name="dialogService"></param>
        public RegionViewModelBase(IRegionManager regionManager, IUnityContainer unityContainer, IDialogService dialogService)
        {
            _isLoding = true;
            _title = new RegionTitle { TitleText = "未命名模板" };
            _dialogService = dialogService;
            _unityContainer = unityContainer;
            RegionManager = regionManager;
            var viewName = this.GetType().Name;
            UriPath = viewName.Replace("ViewModel", "");
        }

        #region 属性
        /// <summary>
        /// 获取系统的<see cref="IRegionManager"/>对象。
        /// </summary>
        protected IRegionManager RegionManager { get; private set; }

        /// <summary>
        /// 获取系统的对话框服务。
        /// </summary>
        public IDialogService Dialog { get { return _dialogService; } }

        /// <summary>
        /// 当前视图标题。
        /// </summary>
        public RegionTitle Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        /// <summary>
        /// 当前视图是否为选择视图。
        /// </summary>
        public bool IsSelected
        {
            get
            {
                return this.isSelected;
            }
            set
            {
                SetProperty(ref isSelected, value);
            }
        }
        #endregion

        #region Command
        /// <summary>
        /// 视图初始化命令。
        /// </summary>
        public ICommand DataLoadCommand
        {
            get
            {
                if (_dataLoadCommand != null) return _dataLoadCommand;
                _dataLoadCommand = new DelegateCommand<object>(OnDataLoadCommandAsync);
                return _dataLoadCommand;
            }
        }

        /// <summary>
        /// 视图关闭命令。
        /// </summary>
        public ICommand ViewCloseCommand
        {
            get
            {
                if (_closeCommand != null) return _closeCommand;
                _closeCommand = new DelegateCommand<object>(onCloseViewCommand);
                return _closeCommand;
            }
        }

        private void onCloseViewCommand(object obj)
        {
            // 通过Unity顶层容器获取对应的类型
            var containerObj = _unityContainer.Registrations.Where(v => v.Name == UriPath).FirstOrDefault();
            string name = containerObj.MappedToType.Name;
            if (!string.IsNullOrEmpty(name))
            {
                var region = RegionManager.Regions["ContentRegion"];
                var view = region.Views.Where(v => v.GetType().Name == UriPath).FirstOrDefault();
                if (view != null)
                    region.Remove(view);
            }
        }

        private void OnDataLoadCommandAsync(object obj)
        {
            try
            {
                OnInitPage(obj);
                _isLoding = false;
            }
            catch (Exception x)
            {
                _isLoding = false;
                var msg = $"页面加载数据失败：" + x.Message;
                LoggerHelper.Current.Error(msg);
                _dialogService.ShowAltert(msg);
            }

        }

        /// <summary>
        /// 页面初始化命令执行时调用此函数。
        /// </summary>
        /// <param name="obj"></param>
        protected virtual void OnInitPage(object obj)
        {

        }
        #endregion

        public virtual void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
        {
            continuationCallback(true);
        }

        public virtual bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public virtual void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        public virtual void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.ContainsKey("Title"))
                Title.TitleText = navigationContext.Parameters["Title"].ToString();
            if (navigationContext.Parameters.ContainsKey("TitleGlyph"))
                Title.TitleGlyph = navigationContext.Parameters["TitleGlyph"].ToString();

            RaisePropertyChanged(nameof(Title));
        }
    }
}
